<?php
    session_start();
?>
<?php
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $code = trim($_POST['code']);   //获取验证码

    //进行必要验证
    if(!strlen($username) || !strlen($password)){
        echo "<script>alert('用户名和密码都必须填写');history.back()</script>";    //history.back返回上一级
        exit;
    } else if(!preg_match("/^[a-zA-Z0-9]{3,10}$/", $username)) {
        echo "<script>alert('用户名填写不符合规范');history.back()</script>";
        exit;
    } else if(!preg_match("/^[a-zA-Z0-9_*]{6,10}$/", $password)) {
        echo "<script>alert('密码填写不符合规范');history.back()</script>";
        exit;
    }

    if(strtolower($code)  == strtolower($_SESSION['captcha'])){
        echo "<script>alert('登录成功');location.href='index.php' </script>";
    } else {
        echo "<script>alert('验证码错误');history.back()</script>";
        exit;
    }

    include_once "connect.php";    //连接数据库
    $sql = "select * from info where username = '$username' and password = '".md5($password)."'";
    $result = mysqli_query($conn, $sql);
    $num = mysqli_num_rows($result);
    if($num) {
        $_SESSION['loginUsername'] = $username;
        //判断是不是管理员
        $info = mysqli_fetch_array($result);
        if($info['admin']) {
            $_SESSION['isAdmin'] = 1;
        } else {
            $_SESSION['isAdmin'] = 0;
        }
        echo "<script>alert('登录成功');location.href='index.php' </script>";
    } else {
        unset($_SESSION['isAdmin']);
        unset($_SESSION['loginUsername']);
        echo "<script>alert('登录失败');history.back()</script>";
    }
